/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistencia;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Gleydson
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public abstract class ImplRepositorioJPA<T> implements Repositorio<T>{


    private EntityManager entityManager;

    private Class<T> persistentClass;

     
    public ImplRepositorioJPA(){
        entityManager = javax.persistence.Persistence.createEntityManagerFactory("SiADPU").createEntityManager();
        this.persistentClass = (Class<T>)
                ((ParameterizedType)getClass().getGenericSuperclass()).
                getActualTypeArguments()[0];
        entityManager.setFlushMode(FlushModeType.AUTO);
    }

    private Class<T> getPersistentClass(){
        return persistentClass;
    }

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager){
        this.entityManager = entityManager;
    }

    protected EntityManager getEntityManager(){
        return entityManager;
    }


    @PersistenceContext
    public T insert(T entity){
        getEntityManager().getTransaction().begin();
        getEntityManager().persist(entity);
        getEntityManager().getTransaction().commit();
        return (T)entity;
    }

    public T getById(Object id){

        T entity = (T)getEntityManager().
                find(getPersistentClass(), id);
        return entity;
    }

    @PersistenceContext
    public void delete(T entity){
        getEntityManager().getTransaction().begin();
        getEntityManager().remove(entity);
        getEntityManager().getTransaction().commit();
    }

    @PersistenceContext
    public void update(T entity){
        getEntityManager().getTransaction().begin();
        getEntityManager().merge(entity);
        getEntityManager().getTransaction().commit();  
    }

    public List<T> getAll(){
        return getEntityManager().createQuery("SELECT e FROM " +persistentClass.getSimpleName()  +" e").getResultList();
    }

    /**
     * @return the queryBuilder
     */
}